package com.yuan.zsschool.ui.wonderful;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.RelativeLayout;

import com.baidu.cloud.media.player.IMediaPlayer;
import com.baidu.cloud.videoplayer.widget.BDCloudVideoView;
import com.yuan.base.framework.BaseAppContext;
import com.yuan.base.framework.BaseFrameworkActivity;
import com.yuan.zsschool.R;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

public class SimplePlayActivity extends BaseFrameworkActivity {

	private BDCloudVideoView bdCloudVideoView;
	private SimpleMediaController simpleMediaController;
	private RelativeLayout rl_holder;
	private RelativeLayout rl_title_layout;

	private Timer barTimer;
	private String url;
	private ProgressDialog mProgressDialog;

	@Override
	protected int getLayoutId() {
		return R.layout.activity_simple_video_playing;
	}

	@Override
	protected void bindViews() {
		rl_title_layout = findViewById(R.id.rl_title_layout);
		rl_holder = findViewById(R.id.rl_holder);
		simpleMediaController = findViewById(R.id.media_controller_bar);

		setOnClickListener(R.id.tv_save_camera, v -> {
			try {
				saveCamera();
			} catch (Exception e) {
				e.printStackTrace();
			}
		});
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

		url = getIntent().getStringExtra("url");
		if (TextUtils.isEmpty(url)) {
			showToast("播放链接错误");
			return;
		}

		bdCloudVideoView = new BDCloudVideoView(this);
		bdCloudVideoView.setVideoPath(url);
		bdCloudVideoView.setVideoScalingMode(BDCloudVideoView.VIDEO_SCALING_MODE_SCALE_TO_FIT);

		RelativeLayout.LayoutParams rllp = new RelativeLayout.LayoutParams(-1, -1);
		rllp.addRule(RelativeLayout.CENTER_IN_PARENT);
		rl_holder.addView(bdCloudVideoView, rllp);

		/**
		 * 注册listener
		 */
		bdCloudVideoView.setOnPreparedListener(new IMediaPlayer.OnPreparedListener() {
			@Override
			public void onPrepared(IMediaPlayer iMediaPlayer) {

			}
		});
		bdCloudVideoView.setOnCompletionListener(new IMediaPlayer.OnCompletionListener() {
			@Override
			public void onCompletion(IMediaPlayer iMediaPlayer) {

			}
		});
		bdCloudVideoView.setOnErrorListener(new IMediaPlayer.OnErrorListener() {
			@Override
			public boolean onError(IMediaPlayer iMediaPlayer, int i, int i1) {
				return false;
			}
		});
		bdCloudVideoView.setOnInfoListener(new IMediaPlayer.OnInfoListener() {
			@Override
			public boolean onInfo(IMediaPlayer iMediaPlayer, int i, int i1) {
				return false;
			}
		});
		bdCloudVideoView.setOnBufferingUpdateListener(new IMediaPlayer.OnBufferingUpdateListener() {
			@Override
			public void onBufferingUpdate(IMediaPlayer iMediaPlayer, int percent) {
				if (simpleMediaController != null && bdCloudVideoView != null) {
					simpleMediaController.onTotalCacheUpdate(percent * bdCloudVideoView.getDuration() / 100);
				}
			}
		});
		bdCloudVideoView.setOnPlayerStateListener(new BDCloudVideoView.OnPlayerStateListener() {
			@Override
			public void onPlayerStateChanged(BDCloudVideoView.PlayerState nowState) {
				if (simpleMediaController != null) {
					simpleMediaController.changeState();
				}
			}
		});
		simpleMediaController.setMediaPlayerControl(bdCloudVideoView);
		bdCloudVideoView.start();

	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onRestart() {
		super.onRestart();
		if (bdCloudVideoView != null) {
			bdCloudVideoView.enterForeground();
		}
	}

	@Override
	protected void onStop() {
		if (bdCloudVideoView != null) {
			bdCloudVideoView.enterBackground();
		}
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (bdCloudVideoView != null) {
			bdCloudVideoView.stopPlayback();
		}
	}

	/**
	 * 检测'点击'空白区的事件，若播放控制控件未显示，设置为显示，否则隐藏。
	 */
	public void onClickEmptyArea(View v) {
		if (barTimer != null) {
			barTimer.cancel();
			barTimer = null;
		}
		if (this.simpleMediaController != null) {
			if (simpleMediaController.getVisibility() == View.VISIBLE) {
				simpleMediaController.hide();
				rl_title_layout.setVisibility(View.GONE);
			} else {
				simpleMediaController.show();
				rl_title_layout.setVisibility(View.VISIBLE);
				hideOuterAfterFiveSeconds();
			}
		}
	}

	private void hideOuterAfterFiveSeconds() {
		if (barTimer != null) {
			barTimer.cancel();
			barTimer = null;
		}
		barTimer = new Timer();
		barTimer.schedule(new TimerTask() {

			@Override
			public void run() {
				if (simpleMediaController != null) {
					simpleMediaController.getMainThreadHandler().post(() -> simpleMediaController.hide());
				}
			}

		}, 5 * 1000);

	}

	public void saveCamera() {
		String fileName = url.substring(0, url.indexOf("?"));
		fileName = fileName.substring(fileName.lastIndexOf("/"), fileName.length());
		//系统相册目录
		String galleryPath = Environment.getExternalStorageDirectory()
				+ File.separator + Environment.DIRECTORY_DCIM
				+ File.separator + "Camera" + File.separator;
		// mDownloadUrl为JSON从服务器端解析出来的下载地址
		RequestParams requestParams = new RequestParams(url);
		// 为RequestParams设置文件下载后的保存路径
		requestParams.setSaveFilePath(galleryPath + fileName);
		// 下载完成后自动为文件命名
		requestParams.setAutoRename(true);
		x.http().get(requestParams, new Callback.ProgressCallback<File>() {
			@Override
			public void onSuccess(File result) {
				try {
					mProgressDialog.dismiss();
				} catch (Exception ignored) {
				}
				showToast("保存成功");
				//通知相册更新
				Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
				Uri uri = Uri.fromFile(result);
				intent.setData(uri);
				BaseAppContext.getInstance().sendBroadcast(intent);
			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {
				showToast("保存失败,请重试");
				try {
					mProgressDialog.dismiss();
				} catch (Exception ignored) {
				}
			}

			@Override
			public void onCancelled(CancelledException cex) {

			}

			@Override
			public void onFinished() {
				mProgressDialog = null;
			}

			@Override
			public void onWaiting() {

			}

			@Override
			public void onStarted() {
				mProgressDialog = new ProgressDialog(SimplePlayActivity.this);
				mProgressDialog.setTitle("正在下载...");
				mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
				mProgressDialog.setMax(100);
				mProgressDialog.setCanceledOnTouchOutside(false);
				mProgressDialog.show();
			}

			@Override
			public void onLoading(long total, long current, boolean isDownloading) {
				mProgressDialog.setProgress((int) (((float) current / (float) total) * 100));
			}
		});
	}

	public interface UploadSuccess {
		void onSuccess(String fileId);
	}
}
